const util = require('util');
const chalk = require('chalk');
const date = require('./date.js');

function getException(rest) {
    try {
        throw Error('');
    } catch (error) {
        const stack = error.stack;
        const stackArr = stack.split('\n');
        let line = ''
        for(var i = 0; i < stackArr.length; i++) {
            var item = stackArr[i];
            if(item.includes(rest)) {
                let arr = stackArr[i+1].split('/');
                line = arr.slice(arr.length-3,arr.length).join('/');
                line = line.split('');
                line = line.join('');
                if(line.endsWith(')')) {
                    line = line.split(')')[0]
                }
                line = '(' + line + ')';
                break;
            }
        }
        return line;
    }
}

function getRest(rest) {
    if(Array.isArray(rest)) {
        let arr = [];
        rest.forEach(item=> {
            if(typeof item == 'object') {
                item = util.inspect(item, {showHidden: false, depth: null})
            }
            arr.push(item)
        })
        return arr;
    }
    if(typeof rest == 'object') {
        rest = util.inspect(item, {showHidden: false, depth: null})
    }
    return rest;
}

$celebr = function(...rest) {
    rest = getRest(rest);
    const position = getException('$celebr');
    const now = date(Date.now(),"MM-dd hh:mm:ss.SS");
    console.log(chalk.green(now,'[CELEBR]',rest),chalk.gray(position))
}

$warn = function(...rest) {
    rest = getRest(rest);
    const position = getException('$warn');
    const now = date(Date.now(),"MM-dd hh:mm:ss.SS");
    console.log(chalk.yellow(now,'[WARN]',rest),chalk.gray(position))
}

$info = function(...rest) {
    rest = getRest(rest);
    const position = getException('$info');
    const now = date(Date.now(),"MM-dd hh:mm:ss.SS");
    console.log(chalk.white(now,'[INFO]',rest),chalk.gray(position))
}


$error = function(...rest) {
    rest = getRest(rest);
    const position = getException('$error');
    const now = date(Date.now(),"MM-dd hh:mm:ss.SS");
    console.log(chalk.red(now,'[ERROR]',rest),chalk.gray(position))
}

$dump = function(...rest) {
    rest = getRest(rest);
    const position = getException('$dump');
    const now = date(Date.now(),"MM-dd hh:mm:ss.SS");
    console.log(chalk.hex('#0abab5')(now,'[DUMP]',rest),chalk.gray(position))
}

module.exports = {
    $celebr,
    $warn,
    $info,
    $error,
    $dump
}